const api = require('../../utils/api.js');
const app = getApp();
const { gatherAction = '', reportAction = '' } = require('../../utils/utils');
const { module: moduleName } = app.siteInfo;
const tools = require('../../utils/getuserinfo.js');
const util = app.util;

Page({
  data: {
    cat_list: [],
    sub_cat_list_scroll_top: 0,
    classa:
      (app.tabbarindex === 0 ? false : true) ||
      app.siteInfo.tabbar_type === '2',
    theme: app.themeData,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '暂无子分类~',
    },
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    toView: '',
    cat_style: 5,
    imgUrl: app.imgUrl,
  },

  onLoad(options) {
    let that = this;
    options = options || {};
    app.pageOnLoad(that);
    this.setData({
      opts: options,
      useTabbar: that.data.useTabbar && app.getTabBarStatus(),
    });
    let parent_id = 0;
    let share_scene = 4;
    let user_id = options.user_id;
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
    }
    if (user_id) {
      parent_id = user_id;
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);

    app.tabbarindex = options.tabbarindex
      ? options.tabbarindex - 0
      : app.tabbarindex;
    let userinfo = wx.getStorageSync('user_info');
    user_id && (app.ws_micro_shop_globalData.parent_id = user_id);
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
      app.loginBindParent({
        parent_id: user_id,
        shop_id: app.ws_micro_shop_globalData.shopid,
        share_scene,
      });
      util.prepareBindInfo(options, moduleName, that);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 &&
          tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        app.getStoreData().then(res => {
          app.loginBindParent({
            parent_id: user_id,
            shop_id: app.ws_micro_shop_globalData.shopid,
            share_scene,
          });
        });
      });
    }

    app.v8_card_seller_actions_log = [];
    
  },

  onShow() {
    wx.setNavigationBarTitle({
      title: '分类',
    });

    this.loadCatStyle();
    if (app.ws_micro_shop_globalData.cat_status) {
      let cat_status = app.ws_micro_shop_globalData.cat_status;
      app.ws_micro_shop_globalData.cat_status = null;
      this.loadData(cat_status);
    } else {
      this.loadData(0);
    }
    app.resetPurchasedNum();
  },

  onHide() {
    reportAction && reportAction();
  },

  onUnload() {
    reportAction && reportAction();
  },

  loadCatStyle() {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.default.catstyle,
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            cat_style: res.data.cat_style,
          });
        }
      },
    });
  },

  loadData(cat_status) {
    let _this = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.cat_list,
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let { list, banner_list, ad_list } = res.data;
          app.wxAppParams(list, 'advert_url');
          _this.setData({
            cat_list: list,
            ad_list: ad_list,
            banner_list: banner_list,
            current_cat: null,
          });
        }
        _this.getClazzList(cat_status);
      },
    });
  },

  catItemClick(e) {
    let target = e.currentTarget.dataset;
    this.setData({
      toView: target.opt,
      cat_status: target.index,
    });

    this.getClazzList(target.index);
    gatherAction &&
      gatherAction('catItemClick', 'success', {
        catID: e.currentTarget.dataset.catId,
      });
  },

  getClazzList(index) {
    let cat_list = this.data.cat_list;
    let scroll_top = 0;
    let current_cat = null;
    for (let i in cat_list) {
      if (Number(i) === Number(index)) {
        cat_list[i].active = true;
        current_cat = cat_list[i];
      } else {
        cat_list[i].active = false;
      }
    }
    this.setData({
      cat_list2: cat_list,
      sub_cat_list_scroll_top: scroll_top,
      current_cat2: current_cat,
    });
  },

  onNavigate(e) {
    let url = e.currentTarget.dataset.url;
    let { cat_status } = this.data;
    cat_status && (app.ws_micro_shop_globalData.cat_status = cat_status);
    app.util.navigateTo(url);
  },

  onCommonNavigator(e) {
    // 跳转公共处理函数
    let page_url;
    let url;
    let RegExp = /^\/pages/;
    if (e.detail && e.detail.item && e.detail.item.data) {
      ({ page_url } = e.detail.item.data);
      url = page_url;
    } else if (e.detail && e.detail.item) {
      ({ url } = e.detail.item);
    } else {
      url = e.currentTarget.dataset.url;
    }
    if (RegExp.test(url)) {
      if (url.indexOf('/book/') > 0) {
        url = `/ws_micro_shop_book${url}`;
      } else if (url.indexOf('/pt/') > 0) {
        url = `/ws_micro_shop_pt${url}`;
      } else if (url.indexOf('/miaosha/') > 0) {
        url = `/ws_micro_shop_ms${url}`;
      } else {
        url = `/ws_micro_shop${url}`;
      }
    }
    e.detail && e.detail.reportName && gatherAction(e.detail.reportName); // 埋点

    if (url.indexOf('https://') !== -1) {
      // url = `/ws_micro_shop/pages/web/web?url=${url}`;
      let param = {};
      let { cat_status } = this.data;
      cat_status && (app.ws_micro_shop_globalData.cat_status = cat_status);
      if (url.indexOf('?') > 0) {
        let str = url.substr(url.indexOf('?') + 1);
        param = {
          [str.substring(0, str.indexOf('='))]: str.substr(str.indexOf('=') + 1),
        };
      }
      url && app.util.navigateTo(url.split('?')[0], param);
    } else {
      url && app.util.navigateTo(url.split('?')[0], this.getQueryVariable(url)); // 未获取网页链接携带的参数
    }
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  onShareAppMessage() {
    let user_info = wx.getStorageSync('user_info');
    let path =
      '/ws_micro_shop/pages/cat/cat?user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    return {
      path,
    };
  },
  onShareTimeline() {
    let user_info = wx.getStorageSync('user_info');
    return {
      title: '',
      imageUrl: '',
      query: 'user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid
    }
  },
  getQueryVariable(url) {
    if (url.indexOf('?') !== -1) {
      // url 中存在参数
      let paraUrl = url.split('?');
      let paraArr = paraUrl[1].split('&');
      let paraObj = {};
      for (let i = 0; i < paraArr.length; i++) {
        let para = paraArr[i].split('=');
        let key = para[0];
        if (key) {
          paraObj = Object.assign(paraObj, {
            [key]: para[1],
          });
        }
      }
      return paraObj;
    } else {
      return {};
    }
  },
});
